//
//  SetPasswordVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/8.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "SetPasswordVC.h"
#import "TopBackView.h"
#import "Common.h"
#import "WKProgressHUD.h"

@interface SetPasswordVC ()<UITextFieldDelegate>

@property (nonatomic,strong) UIView * backview;
@property (nonatomic,strong) UITextField *phoneTextField;
@property (nonatomic,strong) UITextField *captchaTextField;
@property (nonatomic,strong) UITextField *passwordField;
@property (nonatomic,strong) UITextField *againField;

@property (nonatomic,strong) UIButton *captchaButton;
@property (nonatomic) NSInteger secondCountDown;

@property (nonatomic) NSInteger integer1;
@property (nonatomic) NSInteger integer2;

@end

@implementation SetPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"设置提现密码"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = UIviewBackColor;
    
//    _backview = [[UIView alloc]init];
//    _backview.backgroundColor = WhiteColor;
//    _backview.userInteractionEnabled = YES;
//    [self.view addSubview:_backview];
//    [_backview mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerX.mas_equalTo(self.view.mas_centerX);
//        make.top.mas_equalTo(topBackView.mas_bottom).with.offset(10*kHeight);
//        make.size.mas_equalTo(CGSizeMake(Main_Width, cellHeight*4));
//    }];

    
    
    [self initSubViews];
}

#pragma mark - 初始化布局
- (void)initSubViews{
 

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *string = [defaults objectForKey:@"phone"];
    //
    //    if (string == nil) {
    
    
    self.phoneTextField = [[UITextField alloc]init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.text = string;
    self.phoneTextField.userInteractionEnabled = NO;
    
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入短信验证码";
    
    
    self.passwordField = [[UITextField alloc]init];
    self.passwordField.placeholder = @"请输入支付密码，限6位";
    
    self.againField = [[UITextField alloc]init];
    self.againField.placeholder = @"再次确认密码";
    
    self.phoneTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    self.captchaTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordField.keyboardType = UIKeyboardTypeNumberPad;
    self.againField.keyboardType = UIKeyboardTypeNumberPad;
    
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.againField.clearButtonMode = UITextFieldViewModeWhileEditing;

    
    
    //手机号
    UIView *firstV = [self backViewWithFloat:74 andField:self.phoneTextField  andImage:[UIImage imageNamed:@"register_phone"]];
    
    [self.view addSubview:firstV];
    
    //验证码
    UIView *secondV = [self backViewWithFloat:CGRectGetMaxY(firstV.frame) andField:self.captchaTextField  andImage:[UIImage imageNamed:@"register_capture"]];
    
    [self.view addSubview:secondV];
    
    
    //密码
    UIView *thirdV = [self backViewWithFloat:CGRectGetMaxY(secondV.frame) andField:self.passwordField andImage:[UIImage imageNamed:@"register_password"]];
    self.passwordField.secureTextEntry = YES;
    
    [self.view addSubview:thirdV];
    
    UIView *fourthV = [self backViewWithFloat:CGRectGetMaxY(thirdV.frame) andField:self.againField andImage:[UIImage imageNamed:@"icon_passwordToo"]];
    [self.view addSubview:fourthV];
    self.againField.secureTextEntry = YES;
    
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.captchaButton.frame = CGRectMake(screenWidth - 100 * kWidth, (cellHeight - 23)/2.0, 75 * kWidth, 23 * kHeight);
    [self.captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    self.captchaButton.backgroundColor = Color_RGB(253, 243, 232, 1);
    [self.captchaButton addTarget:self action:@selector(captchaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.captchaButton.titleLabel.font = Font(12);
    self.captchaButton.layer.cornerRadius = 5;
    self.captchaButton.layer.borderColor = YellowColor.CGColor;
    self.captchaButton.layer.borderWidth = 0.5;
    
    [firstV addSubview:self.captchaButton];
    
    
    
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(18 , CGRectGetMaxY(fourthV.frame) + 25, screenWidth - 36, 35 * kHeight);
    agreeButton.titleLabel.font = Font(15);
    agreeButton.backgroundColor = YellowColor;
    agreeButton.layer.cornerRadius = 5;
    [agreeButton setTitle:@"完成" forState:UIControlStateNormal];
    [agreeButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [self.view addSubview:agreeButton];
    [agreeButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self initToolBar];
    
}
- (void)initToolBar{
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0,screenWidth, 35 * kHeight)];
    //    [self.view addSubview:toolBar];
    
    UIBarButtonItem *btnPlace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
//    UIBarButtonItem *lastButton = [[UIBarButtonItem alloc]initWithTitle:@"上一个" style:UIBarButtonItemStylePlain target:self action:@selector(lastOneFirstResponser:)];
//    
//    [lastButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
//    
//    
//    UIBarButtonItem *nextButton = [[UIBarButtonItem alloc]initWithTitle:@"下一个" style:UIBarButtonItemStylePlain target:self action:@selector(nextOneFirstResponder:)];
//    
//    [nextButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(keyBoardExit:)];
    
    [doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15 * kHeight], NSFontAttributeName,BlackColor,NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    NSArray *itemsArray = @[btnPlace,btnPlace,doneButton];
    toolBar.items = itemsArray;
    
    self.passwordField.inputAccessoryView = toolBar;
    self.captchaTextField.inputAccessoryView = toolBar;
    self.againField.inputAccessoryView = toolBar;
    
}

- (void)keyBoardExit:(UIBarButtonItem *)sender{
    [self.view endEditing:YES];
}




//确认信息 并返回上一页面
- (void)confirmButton{
        
    [self.view endEditing:YES];
    
    //    1、确认信息
    
    if (self.phoneTextField.text.length <= 0 || self.captchaTextField.text.length <= 0 || self.passwordField.text.length <= 0 || self.againField.text.length <= 0) {
        [WKProgressHUD popMessage:@"请将信息填写完整" inView:self.view duration:1.5 animated:YES];
        
    } else
    
    if (![self.passwordField.text isEqualToString:self.againField.text]) {
        
        [WKProgressHUD popMessage:@"两次密码输入不一致" inView:self.view duration:1.5 animated:YES];

    } else {
    
    NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                          @"pwd":self.passwordField.text,
                          @"usertype":userType,
                          @"code":self.captchaTextField.text};
    
     
    [[Common shared] afPostRequestWithUrlString:set_password parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dictionry = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionry[@"success"] boolValue]) {
            [WKProgressHUD popMessage:dictionry[@"message"]  inView:self.view duration:1.5 animated:YES];
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];

                
            });
            
        } else {
            
            [WKProgressHUD popMessage:dictionry[@"message"]  inView:self.view duration:1.5 animated:YES];

        }
        
        
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    }
    
    
//    //延迟执行
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        //2、返回
//        [self backAction];
//        
//    });
    
}


- (void)showAlertWithString:(NSString *)string{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1   = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2   = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (UIView *)backViewWithFloat:(CGFloat)y
                     andField:(UITextField *)textField
                     andImage:(UIImage *)image{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10*kWidth, y, screenWidth-20*kWidth, cellHeight)];
    view.backgroundColor = WhiteColor;
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(28 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 100, view.frame.size.height);
    textField.font = Font(12);
    [view addSubview:textField];
    textField.delegate = self;
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, view.frame.size.height - 0.5, screenWidth - 36, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}






#pragma mark - 验证码方法
- (void)captchaButtonAction:(UIButton *)sender{
    
    //先判断手机号的正确
    NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
    BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
    if (isRight) {
        
        
        NSString *urlString = [NSString stringWithFormat:@"%@accntLedger/sendMessage",Main_interface];
        NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                              @"usertype":userType};
        
        
        Common *c = [[Common alloc]init];
        
        [ c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [WKProgressHUD popMessage:dict[@"message"] inView:self.view duration:1.5 animated:YES];

            if ([dict[@"success"] boolValue]) {
                
                [sender setTintColor:WhiteColor];
                sender.userInteractionEnabled = NO;
                _secondCountDown = 60;
                NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
                [time fire];

                
            } else {
                
                [WKProgressHUD popMessage:dict[@"message"] inView:self.view duration:1.5 animated:YES];

            }
            
        } failedBlock:^(NSString *errorMsg) {
            
            NSLog(@"%@",errorMsg);
            
        }];
        
        
    } else {
        
        [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];
        
    }
    
}

- (void)timeFireAction:(NSTimer *)time{
    _secondCountDown --;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%ds)",(int)_secondCountDown]];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
    
    
    if (_secondCountDown <= 0) {
        [time invalidate];
        self.captchaButton.userInteractionEnabled = YES;
        //设置button下划线
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"重新发送"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
        //        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        
        [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
        
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForeground:) name:@"foreground" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackground:) name:@"background" object:nil];
    
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)appGoBackground:(NSNotification *)notification{
    
    _integer1 = [notification.userInfo[@"time"] integerValue];
    
}

- (void)appGoForeground:(NSNotification *)notification{
    NSInteger integer = [notification.userInfo[@"time"] integerValue];
    
    _integer2 = (integer - _integer1)/1000;
    
    _secondCountDown = _secondCountDown - _integer2;
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - 导航栏返回
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
    
}




@end
